package com.wy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wy.dto.DishDto;
import com.wy.entity.Dish;
import com.wy.entity.DishFlavor;
import com.wy.mapper.DishMapper;
import com.wy.service.DishFlavorService;
import com.wy.service.DishService;
import com.zaxxer.hikari.util.FastList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * 新增菜品,同时将菜品的口味进行保存
     * @param
     */
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //1.首先保存菜品的基本信息
        this.save(dishDto);
        //2.保存菜品口味
            //需要获取菜品的id值,将id值和口味进行一个绑定
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item)->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        //3.保存到菜品口味表dish_flavors
        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //1.查询商品信息,dish表
        Dish dish = this.getById(id);
        //2.查询商品口味信息,dish_flavor表
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavorList = dishFlavorService.list(queryWrapper);
        //3.页面需要的是一个Dto对象,new一个,对上面的数据进行复制,并且让flavors赋值给Dto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(flavorList);
        //4.最后返回dishDto
        return dishDto;
    }

    /**
     * 更新菜品,重点包括菜品的口味
     * @param dishDto
     */
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //1.更新dish的信息
        this.updateById(dishDto);
        //2.清理原来的flavor口味的信息——dish_flavor的delete操作
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //3.添加当前提交过来的口味数据——dish_flavor的insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();
        //和新增中一样,需要处理口味中匹配的id
        flavors = flavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        //4.执行保存数据
        dishFlavorService.saveBatch(flavors);
    }
}
